<?php

declare(strict_types=1);

namespace App\Helpers;

/**
 * 斗拱支付
 */
class DougongPayUtil
{
    //支付链接
    const PAY_LINK = "https://api.huifu.com/v2/trade/payment/jspay";
    //系统号(商户号)
    const SYS_ID ='6666000164636033';
    //产品号
    const PRODUCT_ID = 'EDUSTD';
    //商户号
    const HUIFU_ID = '6666000165631783';
    //回调地址
    const NOTIFY_URL = 'https://api.jun131419.com/callback/dougong_pay';
    //
    const WX_APPID = 'wxb7e1f844fef823e2';
 
    // //系统号(商户号)
    // const SYS_ID_2 ='6666000167474071';
    // //商户号 小君微信
    // const HUIFU_ID_2 = '6666000167474071';
    // //APPID 小君微信
    // const WX_APPID_2 = 'wx18af8941701fa8a1';


    //系统号(商户号)
    const SYS_ID_2 ='6666000169395354';
    //商户号 xin微信
    const HUIFU_ID_2 = '6666000169395354';
    //APPID 新微信
    const WX_APPID_2 = 'wxa4887f6d4b618579';


 
    /**
     * 充值下单
     */
    static function orderCreateDougong($orderInfo = [], $channel = '')
    {
     	$rounded = round($orderInfo['trans_amt']/100,2);
	$trans_amt = number_format($rounded, 2, '.', ''); // 格式化为两位小数

	if ($channel == 'dg_wechat') {
            $data['wxdata']['sub_appid'] = self::WX_APPID_2;
            $huifuId = self::HUIFU_ID_2;
            $sysId = self::SYS_ID_2;
        } else {
            $huifuId = self::HUIFU_ID;
            $sysId = self::SYS_ID;
        }

	$data = [
            //日期格式
            'req_date' => $orderInfo['req_date'],
            //请求流水号
            'req_seq_id' => $orderInfo['req_seq_id'],
            'huifu_id' => $huifuId,
            'goods_desc' => '充值',
            //交易类型
            'trade_type' => $orderInfo['trade_type'],
            // 交易金额
            'trans_amt' => $trans_amt,
            'notify_url' => self::NOTIFY_URL,
    	];

	if ($channel == 'dg_wechat') {
	    $result = array(
		'data' => array(
		    'req_seq_id' => $orderInfo['req_seq_id'],
		    'qr_code' => '',
		),    
	    );
	    return $result;
	}

	if ($channel != 'dg_wechat') {
            //私钥
            $rsaPrivateKey = config('dougong.private_key');
        } else {
            //私钥 小君微信
            $rsaPrivateKey = config('dougong2.private_key');
        }

        $post_array = [
            'sys_id' => $sysId,
            'product_id' => self::PRODUCT_ID,
            'data' => $data,
    	];
        ksort($data); 
//	return [$data,$channel];
	$sign_json = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
	$sign = self::sha_with_rsa_sign($sign_json,$rsaPrivateKey);
	
	$post_array['sign'] = $sign;  
	ksort($post_array);
	//return $post_array;
	$result = self::curlPost(self::PAY_LINK, $post_array);
        return $result;
    }

    /*
    * 发送请求
    * @param $url
    * @param $param
    * @return bool|mixed
    * @throws Exception
    */
    static function curlPost($url, $postData){
        // 初始化 cURL
        $ch = curl_init();

        // 配置 cURL 选项
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true, // 返回响应而不是直接输出
            CURLOPT_POST => true, // 使用 POST 方法
            CURLOPT_POSTFIELDS => json_encode($postData), // 发送 JSON 数据
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer your_access_token' // 认证头
            ],
            CURLOPT_TIMEOUT => 30, // 超时设置
            CURLOPT_SSL_VERIFYPEER => true // 生产环境应保持为 true
        ]);

        // 执行请求
        $response = curl_exec($ch);
//return $response;	
        // 检查错误
        if (curl_errno($ch)) {
            throw new Exception('cURL Error: ' . curl_error($ch));
        }

        // 获取 HTTP 状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // 关闭 cURL 资源
        curl_close($ch);

        // 处理响应
        if ($httpCode === 200) {
            $data = json_decode($response, true);
	    return $data;
	    // 处理返回的数据
        } else {
            // 处理错误
            throw new Exception("API 请求失败，状态码: $httpCode");
        }
    }

    /**
     * 私钥加签（对数据源排序），可用于 V2 版本接口数据加签
     *
     * @param array $data 原数据( 排序后的json字符串; 数组参数排序后转json字符串(数据的中文和斜杠均不转码):
     *
     * @param string $rsaPrivateKey 私钥
     * @param int $alg 默认 OPENSSL_ALGO_SHA256
     *
     * @return string 签名串
     */
    static function sha_with_rsa_sign($data, $rsaPrivateKey, $alg=OPENSSL_ALGO_SHA256){
       // ksort($data);
       // json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        $key = "-----BEGIN PRIVATE KEY-----\n".wordwrap($rsaPrivateKey, 64, "\n", true)."\n-----END PRIVATE KEY-----";
        $signature= '';
        try {
            openssl_sign($data, $signature, $key, $alg);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        return base64_encode($signature);
    }
}
